#include <QDebug>
#include <QImage>

#include "uartcamera.h"

extern bool is_detect_jpg_code;

UartCamera::UartCamera(QObject *parent) : QObject(parent)
{
    port = nullptr;
    isRecveImg = false;
//    request_timer = new QTimer();
//    request_timer->setInterval(150);
//    connect(request_timer,SIGNAL(timeout()),this,SLOT(SlotSendRequest()));

}


void UartCamera::SetSerialPort(QSerialPort* p)
{
    port = p;
    isRecveImg = false;
    connect(port,SIGNAL(readyRead()),this,SLOT(SlotGetUartImg()));
}

void UartCamera::SlotSendRequest()
{
    QString cmd = "sd";
    port->write(cmd.toLatin1());
}

void UartCamera::SlotGetUartImg()
{
    QByteArray block = port->readAll();
//    int block_size = block.size();
//    qDebug()<<block_size;
    if(isRecveImg)
    {
        img_buf.append(block);
    }

    if((block[0]==0xFF) &&(block[1]==0xD8))
    {
        isRecveImg = true;
//        qDebug()<<"start recv one";
        img_buf.clear();
        img_buf.append(block);
    }

    if((block[block.size()-1]==0xD9) &&(block[block.size()-2]==0xFF))
    {
        isRecveImg = false;
        img_buf.append(block);

        QImage img(320,240,QImage::Format_ARGB8565_Premultiplied);
        img = QImage::fromData(img_buf,"JPEG");
        if(!is_detect_jpg_code)
        {
//            ui->labelImg->setPixmap(QPixmap::fromImage(img));
//            qDebug()<<"finish recv one,img buf size:"<<img_buf.size();
            emit SigPixBuf(img_buf);
        }
        else
        {
            is_detect_jpg_code = false;
        }
        img_buf.clear();
    }

    if((!isRecveImg) && (block[0]=='@') && (block[block.size()-1]=='#'))
    {
        QString get_data = block;
        qDebug()<<"get label data:"<< get_data;
    }

}
